<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 第三方账号获取token
// +----------------------------------------------------------------------
namespace app\api\service;

use app\lib\exception\TokenException;
use app\model\Admin;

class AppToken extends Token
{
  public function get($ac, $se)
  {
    $app = Admin::check($ac, $se);
    if (!$app) {
      throw new TokenException([
        'msg' => '授权失败',
        'errorCode' => 10004
      ]);
    }
    else {
      
      $scope = $app->scope;
      $uid = $app->id;
      $values = [
        'scop' => $scope,
        'uid' => $uid
      ];
      $token = $this->saveToCache($values);
      admin::login($app);
      return $token;
    }
  }

  private function saveToCache($values)
  {
    $token = self::generateToken();
    $expire_in = config('setting.token_expire_in');
    $result = cache($token, json_encode($values), $expire_in);
    if (!$result) {
      throw new TokenException([
        'msg' => '服务器缓存异常',
        'errorCode' => 10005
      ]);
    }
    return $token;
  }

}
?>